//
//  Person.swift
//  JKSQLite
//
//  Created by 王冲 on 2018/5/1.
//  Copyright © 2018年 希艾欧科技有限公司. All rights reserved.
//

import UIKit

class Person: NSObject {

    @objc var id: Int = 0
    @objc var age: Int = 0
    @objc var name: String?
    
    
    
    /**
        异步插入一条记录
     */
    func insertQueuePerson()
    {
        
        assert(name != nil, "必须要给name赋值")
        JKSQLiteManger.shareManger().execQueueSQL { (manager) -> () in
            // 1.编写SQL语句
            let sql = "INSERT INTO T_Person8" +
                "(name, age)" +
                "VALUES" +
            "('\(self.name!)', \(self.age));"
            // 2.执行SQL语句
            if manager.execSQL(sql: sql){
                
                //print("插入成功=\(String(describing: self.name))")
            }
            //print(Thread.current)
        }
        
    }
    
    
    // MARK: 查询数据
    // MARK: - 执行数据源CRUD的操作
    
    class func loadPersons() -> [Person]
    {
        let sql = "SELECT * FROM T_Person8;"
        let res = JKSQLiteManger.shareManger().execRecordSQL(sql: sql)
        var models = [Person]()
        for dict in res
        {
            models.append(Person(dict: dict))
        }
        return models
    }
    
    // MARK: 删除数据
    func deletePerson() -> Bool {
        
        // 1、编写SQLite语句
        let sql = "DELETE FROM T_Person8 WHERE age = \(self.age);"
        // 2、执行SQLite语句
        return JKSQLiteManger.shareManger().execSQL(sql: sql)
    }
    
    // MARK: 更新数据
    func updatePerson(name: String) -> Bool {
        
        // 1、编写SQLite语句
        let sql = "UPDATE T_Person8 SET name = '\(name)' WHERE age = \(self.age);"
        // 2、执行SQLite语句
        return JKSQLiteManger.shareManger().execSQL(sql: sql)
    }
    
    // MARK: 执行数据源 CRUD的操作
    /**
       插入一条数据
     */
    func insertPerson() -> Bool {
        
        assert(name != nil, "必须要给name赋值")
        
        // 1、编写SQLite语句
        let sql = "INSERT INTO T_Person8 (name,age) VALUES ('\(name!)',\(age));"
        // 2、执行SQLite语句
        return JKSQLiteManger.shareManger().execSQL(sql: sql)
  
    }
    
    
    // MARK: 系统内部的方法
    init(dict: [String: AnyObject]) {
        
        super.init()
        setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
        print("\(key)")
        
    }
    
    override var description: String{
        
        return "id = \(id),age = \(age),name = \(name!)"
    }
    
}
